package com.oss;



import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.oss.properties.FileType;
import com.oss.properties.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component
public class OSSFileUtils implements FileUtilService {
    @Autowired
    IDService idService;
    @Autowired
    OSSClient ossClient;
    @Autowired
    FileType fileType;
    @Autowired
    OSSProperties op;

    @Value("${steel.file.folder}")
    String folder;

    public List<String> uploads(List<MultipartFile> files) {
        if (files.isEmpty()) {
          //  throw SteelException.create(ExceptionConstant.FileArguments);
        }
        List<String> list = new ArrayList();
        files.forEach(d -> {
            val a = upload(d);
            list.add(a);
        });
        return list;
        //return files.stream().map(this::upload).collect(Collectors.toList());
    }


    public void download(OutputStream os, String icon) {
        try {
            val ossObject = ossClient.getObject(op.getBucketName(), icon);
            // 读取文件
            val in = new BufferedInputStream(ossObject.getObjectContent());
            val out = new BufferedOutputStream(os);
            byte[] buffer = new byte[1024];
            int lenght = 0;
            while ((lenght = in.read(buffer)) != -1) {
                out.write(buffer, 0, lenght);
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     */
    public String upload(MultipartFile file) {
        try {
            val key = idService.generateID() + file.getOriginalFilename();
            if (key.contains("(")) {
                key.replace("(", "");
            }
            if (key.contains(")")) {
                key.replace(")", "");
            }
            //删除特殊字符
            String regEx = "[\n`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
            String aa = "";
            String newKey = key.replaceAll(regEx, aa);
            if (FileType.getFileByFile(file.getInputStream()) == null) {
              //  throw SteelException.create(400, "请输入正确的文件类型");
            }
            val result = ossClient.putObject(op.getBucketName(), folder + newKey, file.getInputStream());

            log.info("upload_result: {}", result);
            return op.getCdn() + folder + newKey;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 上传文件
     *
     * @param inputStream 流
     * @param path        保存地址
     * @return
     */
    public String upload(InputStream inputStream, String path) {
        try {
            PutObjectResult result = ossClient.putObject(op.getBucketName(), path, inputStream);
           // log.info("upload_result: {}", result);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
